const router = require("@koa/router")();
const user = require("./api/user")
const home = require("./api/home")
const fs = require('fs');
const path = require("path")
const { getAccessToken, createQRCode, } = require("../request/wx")
const { getCode2Session } = require("../request/tt")
const { appid, secret, ttappid, ttsecret } = require("../config/index")

let access_token;
router.get("/QRCode", async (ctx) => {
  try {
    /* 判断凭证是否存在 */
    if (!access_token) {
      const res = await getAccessToken(appid, secret)
      if (res.errcode) {
        ctx.body = {
          state: 0,
          message: res.errmsg
        }
        return
      }
      access_token = JSON.parse(res.body).access_token
    }
    /* 判断二维码是否存在 */
    try {
      const res = await fs.promises.access(path.join(__dirname, '../upload/wx/qrCode.png'));
      ctx.body = {
        state: 1,
        message: "成功",
        data: "http://127.0.0.1:8000/upload/wx/qrCode.png"
      };
    } catch (error) {
      console.log(error)
      const buffer = await createQRCode(access_token, { path: "pages/index/index" })
      if (!buffer.errcode) {
        fs.writeFile(path.join(__dirname, '../upload/wx/qrCode.png'), buffer.body, function (err) {
          if (err) throw err;
        });
        ctx.body = {
          state: 1,
          message: "成功",
          data: "http://127.0.0.1:8000/upload/wx/qrCode.png"
        };
      }
    }
  } catch (error) {
    // console.log(error)
    ctx.body = {
      state: 0,
      message: "失败",
      data: error
    };
  }

})
router.post("/ttOpenid", async (ctx) => {
  const code = ctx.request.body.code;

  const res = await getCode2Session(ttappid, ttsecret, code)
  if (res.errcode) {
    ctx.body = {
      state: 0,
      message: res.errmsg
    }
    return
  }
  ctx.body = res.body
})
// router.use("/", async (ctx, next) => {
//   console.log("===>",ctx)
// })
router.use("/user", user.routes());
router.use("/home", home.routes())

module.exports = router